package com.ruoyi.client.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.client.domain.ShoppingCart;
import com.ruoyi.client.mapper.ShoppingCartMapper;
import com.ruoyi.client.pojo.vo.CartVo;
import com.ruoyi.client.service.IShoppingCartService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements IShoppingCartService {
    @Resource
    private ShoppingCartMapper cartMapper;

    @Override
    public boolean add(ShoppingCart cart) {
        //购物车商品不能有重复项,如果重复，则累加数量
        ShoppingCart cartDb = cartMapper.selectByUserIdAndProductId(cart.getUserId(), cart.getProductId());
        if (ObjectUtil.isNotNull(cartDb)) {
            //数据库中已有记录，则累加//
            Long count = cartDb.getCount() + cart.getCount();
            cartDb.setCount(count);
            return cartMapper.update(cartDb) > 0;
        } else {
            //数据库中没有记录，新增
            cart.setId(null);
            return cartMapper.add(cart) > 0;
        }
    }

    @Override
    public List<CartVo> list(Long userId) {
        return cartMapper.list(userId);
    }

    @Override
    public boolean delete(String ids) {
        // 将字符串ids 转数组
        long[] idArray;
        idArray = StrUtil.splitToLong(ids,","); //使用Hutool工具类
        return cartMapper.delete(idArray);
    }

    @Override
    public boolean deleteAll(Long userId) {
        return cartMapper.deleteAll(userId);
    }

    @Override
    public boolean update(ShoppingCart cart) {
        return cartMapper.update(cart)>0;
    }

    @Override
    public boolean updateCheckedAll(Long userId, Boolean isChecked) {
        return cartMapper.updateCheckedAll(userId,isChecked)>0;
    }

    @Override
    public List<CartVo> listChecked(Long userId) {
        return cartMapper.listChecked(userId);
    }
}
